package com.itheima.comment.service.impl;

import com.alibaba.fastjson.JSON;
import com.itheima.article.feign.ApArticleFeign;
import com.itheima.article.pojo.ApArticle;
import com.itheima.comment.docs.ApCommentDocument;
import com.itheima.comment.docs.ApCommentLikeDocument;
import com.itheima.comment.docs.CommentVo;
import com.itheima.comment.dto.CommentDto;
import com.itheima.comment.dto.CommentLikeDto;
import com.itheima.comment.dto.CommentSaveDto;
import com.itheima.comment.pojo.ApComment;
import com.itheima.comment.mapper.ApCommentMapper;
import com.itheima.comment.service.ApCommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.pojo.PageInfo;
import com.itheima.common.pojo.Result;
import com.itheima.common.util.RequestContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * APP评论信息表 服务实现类
 * </p>
 *
 * @author 作者
 * @since 2021-09-01
 */
@Service
public class ApCommentServiceImpl extends ServiceImpl<ApCommentMapper, ApComment> implements ApCommentService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private ApArticleFeign apArticleFeign;

    /***
     * 分页查询文章评论列表
     * @param dto
     * @return
     */
    @Override
    public PageInfo<CommentVo> loadPage(CommentDto dto) {
        //1:分页查询评论列表，根据点赞数量降序
        Query query = Query.query(Criteria.where("entryId").is(dto.getArticleId()));
        query.with(Sort.by(Sort.Direction.DESC,"likes"));
        query.with(PageRequest.of((dto.getPage().intValue()-1),dto.getSize().intValue()));
        //评论列表数据
        List<ApCommentDocument> apCommentDocuments = mongoTemplate.find(query, ApCommentDocument.class);
        List<CommentVo> vos = new ArrayList<CommentVo>();
        List<String> ids = new ArrayList<String>();
        for (ApCommentDocument apCommentDocument : apCommentDocuments) {
            CommentVo vo = new CommentVo();
            BeanUtils.copyProperties(apCommentDocument,vo);
            vos.add(vo);
            ids.add(apCommentDocument.getId());
        }
        //List<CommentVo> vos = JSON.parseArray(JSON.toJSONString(apCommentDocuments),CommentVo.class);

        //评论总数量查询
        Query countQuery = Query.query(Criteria.where("entryId").is(dto.getArticleId()));
        long count = mongoTemplate.count(countQuery, ApCommentDocument.class);

        //2：检查当前用户是否对评论列表中的评论信息点赞->查询
        //0:获取用户信息
        String token = RequestContext.getNode("token");
        if(!StringUtils.isEmpty(token)){
            Integer userId = RequestContext.getNodeValue("id");
            Query commentQuery = Query.query(Criteria.where("authorId").is(userId).and("commentId").in(ids));
            List<ApCommentLikeDocument> likes = mongoTemplate.find(commentQuery, ApCommentLikeDocument.class);
            for (CommentVo vo : vos) {
                for (ApCommentLikeDocument like : likes) {
                    if(like.getCommentId().equals(vo.getId())){
                        vo.setOperation(like.getOperation());
                        break;
                    }
                }
            }
        }
        //分页处理
        Long pages = count%dto.getSize()==0? count/dto.getSize()  : count/dto.getSize()+1;
        PageInfo<CommentVo> pageInfo = new PageInfo<CommentVo>(dto.getPage(),dto.getSize(),count,pages,vos);
        return pageInfo;
    }

    /***
     * 点赞实现
     * @param dto
     */
    @Override
    public void likes(CommentLikeDto dto) {
        //0:获取用户信息
        Integer userId = RequestContext.getNodeValue("id");
        String name = RequestContext.getNodeValue("name");
        String image = RequestContext.getNodeValue("image");

        if(dto.getOperation()==0){
            //1:点赞->添加1条点赞记录
            ApCommentLikeDocument likeDoc = new ApCommentLikeDocument();
            likeDoc.setAuthorId(userId);
            likeDoc.setCommentId(dto.getCommentId());
            likeDoc.setOperation(dto.getOperation());
            mongoTemplate.save(likeDoc);

            //2：被点赞的评论点赞数量递增
            ApCommentDocument commentDoc = mongoTemplate.findById(dto.getCommentId(), ApCommentDocument.class);
            commentDoc.setLikes(commentDoc.getLikes()+1);
            mongoTemplate.save(commentDoc);
        }else{
            //3：取消点赞->点赞记录处理
            Query query =Query.query(Criteria.where("authorId").is(userId).and("commentId").is(dto.getCommentId()));
            ApCommentLikeDocument likeDoc = mongoTemplate.findOne(query, ApCommentLikeDocument.class);
            likeDoc.setOperation(1);
            mongoTemplate.save(likeDoc);

            //4：被取消点赞的评论点赞数量递减
            ApCommentDocument commentDoc = mongoTemplate.findById(dto.getCommentId(), ApCommentDocument.class);
            commentDoc.setLikes(commentDoc.getLikes()-1);
            mongoTemplate.save(commentDoc);
        }
    }

    /***
     * 评论信息保存到MongoDB中
     * @param dto
     */
    @Override
    public void saveToMongo(CommentSaveDto dto) {
        //0：获取用户信息
        Integer userId = RequestContext.getNodeValue("id");
        String name = RequestContext.getNodeValue("name");
        String image = RequestContext.getNodeValue("image");
        Result<ApArticle> articleResult = apArticleFeign.findById(dto.getArticleId());
        ApArticle article = articleResult.getData();

        //1：创建ApCommentDocument
        //2：完善
        ApCommentDocument doc = new ApCommentDocument();
        doc.setAuthorId(userId);
        doc.setAuthorName(name);
        doc.setEntryId(dto.getArticleId());
        doc.setChannelId(article.getChannelId()); //频道ID
        doc.setType(0);  //类型
        doc.setContent(dto.getContent());
        doc.setImage(image);
        doc.setLikes(0);
        doc.setReply(0);
        doc.setFlag(0);
        doc.setOrd(1);
        doc.setCreatedTime(LocalDateTime.now());
        doc.setUpdatedTime(LocalDateTime.now());
        //3：增加操作
        mongoTemplate.save(doc);
    }
}
